<template>
  <el-row
    :gutter="10"
    class="mb-0!"
    :class="[
      footer
        ? '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height)-10px)]'
        : '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-20px)]'
    ]"
  >
    <el-col :xs="24" :sm="12" :md="10" :lg="7" :xl="6">
      <User>
        <template #backButton>
          <el-button
            @click="goReturnUrl('cancel')"
            size="large"
            plain
            type="primary"
            class="w-full custom-text-18 !h-50px"
          >
            返回
          </el-button>
        </template>
      </User>
    </el-col>
    <el-col :xs="24" :sm="12" :md="14" :lg="17" :xl="18">
      <el-row :gutter="10" class="!h-full">
        <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18" class="pos-relative">
          <ContentWrap
            class="mb-0!"
            :class="[
              footer
                ? '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height)-10px)]'
                : '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-20px)]'
            ]"
            :bodyStyle="{ height: '100%', padding: '0 0 10px 0' }"
          >
            <div class="flex flex-col !h-full justify-between">
              <div class="flex">
                <ContentWrap class="!w-full border-none! mb-0! p-10px" :body-style="{ padding: 0 }">
                  <el-row class="!w-full m-x-0!" justify="space-between">
                    <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                      <div class="flex items-center">
                        <el-text truncated class="custom-text-18">销售员工</el-text>
                        <div class="ml-10px">
                          <SystemUserShowcase
                            ref="UserShowcaseRef"
                            v-model:model-value="state.employeeStr"
                            @change="setEmployeeConfirm()"
                            :show-system-users="false"
                            :icon-szie="28"
                          />
                        </div>
                      </div>
                    </el-col>
                    <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                      <div class="flex items-center justify-end">
                        <ClearingDate
                          v-model:date-time="state.orderPayload.repairDate"
                          v-model:is-check="state.orderPayload.isRepair"
                          class="ml-10px"
                        >
                          <div class="flex items-center">
                            <el-text truncated class="custom-text-18">补录充值:</el-text>
                          </div>
                        </ClearingDate>
                      </div>
                    </el-col>
                  </el-row>
                </ContentWrap>
              </div>
              <el-divider border-style="dashed" class="m-y-0!" />
              <el-scrollbar viewClass="flex-grow mt-10px p-x-10px">
                <el-row class="mx-0px! mb-15px">
                  <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <div>
                      <el-form-item label="赠送金额">
                        <template #label>
                          <span class="custom-text-16">赠送金额</span>
                        </template>
                        <el-switch
                          class="ml-10px"
                          @change="handelChange"
                          :disabled="state.packageId != ''"
                          v-model="state.isGiveMoney"
                        />
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="15" class="mb-15px">
                  <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                    <div>
                      <el-form-item label="充值" class="flex items-center">
                        <template #label>
                          <span class="custom-text-16">充值</span>
                        </template>
                        <el-input
                          v-model="state.rechargeMoeny"
                          class="h-50px! custom-text-24!"
                          :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                  </el-col>
                  <el-col v-if="state.isGiveMoney" :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                    <div>
                      <el-form-item label="赠送" class="flex items-center">
                        <template #label>
                          <span class="custom-text-16">赠送</span>
                        </template>
                        <el-input
                          v-model="state.giveMoney"
                          class="h-50px! custom-text-24!"
                          :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                <el-row class="mx-0px! mb-15px">
                  <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <div>
                      <el-form-item label="赠送积分">
                        <template #label>
                          <span class="custom-text-16">赠送积分</span>
                        </template>
                        <el-switch
                          class="ml-10px"
                          @change="handelChange"
                          :disabled="state.packageId != ''"
                          v-model="state.isGiveIntegral"
                        />
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="15" v-if="state.isGiveIntegral">
                  <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                    <div>
                      <el-form-item label="积分" class="flex items-center">
                        <template #label>
                          <span class="custom-text-16">积分</span>
                        </template>
                        <el-input
                          class="h-50px! custom-text-24!"
                          v-model="state.giveIntergral"
                          :formatter="(value: string) => verifiyNumberInteger(value)"
                        >
                          <template #append>分</template>
                        </el-input>
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                <el-divider class="my-10px!"
                  ><span class="custom-text-18">充值套餐</span></el-divider
                >
                <div class="flex flex-wrap mt-20px">
                  <el-button
                    class="h-100px! w-180px! pos-relative mb-10px ml-0! mr-10px!"
                    style="white-space: pre-warp"
                    v-for="item in state.packageList"
                    :key="item.money"
                    :type="state.packageId === item.id ? 'primary' : ''"
                    @click="onSelect(item)"
                  >
                    <div class="custom-text-26"> {{ fenToYuan(item.payPrice) }} 元</div>
                    <el-text
                      class="pos-absolute bottom-0 left-0 w-180px! whitespace-pre-wrap!"
                      v-if="item.bonusPrice || item.growPrice || item.pointPrice"
                      :type="state.packageId === item.id ? '' : 'primary'"
                      :class="state.packageId === item.id ? 'text-white!' : ''"
                    >
                      送
                      <span class="custom-text-14" v-if="item.bonusPrice > 0">
                        {{ fenToYuan(item.bonusPrice) }} 元
                      </span>
                      <span class="custom-text-14" v-if="item.pointPrice > 0">
                        {{ item.pointPrice }} 分
                      </span>
                      <span class="custom-text-14" v-if="item.growPrice > 0">
                        {{ item.growPrice }} 经验值
                      </span>
                    </el-text>
                    <!-- <el-tag
                      class="pos-absolute bottom-0 left-0"
                      type="primary"
                      v-if="item.bonusPrice || item.growPrice || item.pointPrice"
                      :effect="state.rechargeMoeny === fenToYuan(item.payPrice) ? '' : 'dark'"
                    >
                      送
                      <span class="custom-text-14" v-if="item.bonusPrice > 0">
                        {{ fenToYuan(item.bonusPrice) }} 元
                      </span>
                      <span class="custom-text-14" v-if="item.pointPrice > 0">
                        {{ item.pointPrice }} 分
                      </span>
                      <span class="custom-text-14" v-if="item.growPrice > 0">
                        {{ item.growPrice }} 经验值
                      </span>
                    </el-tag> -->
                  </el-button>
                </div>
              </el-scrollbar>
            </div>
          </ContentWrap>
        </el-col>
        <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
          <OrderInfo :cart-employee-text="cartEmployeeText" :order-info="state">
            <template #button>
              <el-button
                type="primary"
                size="large"
                class="w-100% custom-text-18 !h-50px"
                @click="onHandleConfirm"
                >确认订单</el-button
              >
            </template>
          </OrderInfo>
        </el-col>
      </el-row>
    </el-col>
  </el-row>

  <!-- 支付弹框 -->
  <PayDialog
    ref="payDialogRef"
    :no="orderId"
    :dialog-visible="state.showPayDialog"
    :payment-map="state.paymentMap"
    :order-info="state.orderInfo"
    :scene-type="'second'"
    @success="handleUpdate"
    @close="
      () => {
        state.showPayDialog = false
      }
    "
  />
  <!-- 音频 -->
  <audio ref="audioRef" controls v-show="false">
    <source :src="audioUrl" />
  </audio>
</template>

<script lang="ts" setup>
defineOptions({ name: 'ShopPayCashier' })
import { useTagsViewStore } from '@/store/modules/tagsView'
import User from '@/views/shop/components/member/user/index.vue'
import noPaymentAudioUrl from '@/assets/audio/nonPayment.mp3'
import successPaymentAudioUrl from '@/assets/audio/paymentSuccess.mp3'
import { verifyNumberIntegerAndFloat, verifiyNumberInteger } from '@/utils/formatter'
import { fenToYuan } from '@/utils'
import * as OrderApi from '@/api/shop/trade/order'
import * as PayOrderApi from '@/api/shop/trade/pay'

const appStore = useAppStore()
const footer = computed(() => appStore.getFooter)
import ClearingDate from '@/views/shop/components/clearingDate/index.vue' //补录

import OrderInfo from './components/OrderInfo.vue'
import PayDialog from '@/views/shop/components/payDialog/index.vue' //支付弹框
import { useTagsView } from '@/hooks/web/useTagsView'
const { closeSelectedTag } = useTagsView()

/**
 * 音频播放
 */
const audioUrl = ref()
const audioRef = ref<any>(null)
const playAudio = (type) => {
  if (type == 'nonPayment') {
    audioRef.value.src = noPaymentAudioUrl
  } else if (type == 'successPayment') {
    audioRef.value.src = successPaymentAudioUrl
  }
  audioRef.value?.play()
}
/** 员工选择 */
import SystemUserShowcase from '@/views/shop/components/system/user/systemUserShowcase.vue'
/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()

const message = useMessage() // 消息弹窗
/** 购物车信息 */
import { useAppStore } from '@/store/modules/app'
import { useShopCartStoreWithOut } from '@/store/modules/shop/cart'

const shopCartStore = useShopCartStoreWithOut()

/** 密码键盘信息 */
import { ElNotification } from 'element-plus'
import { convertToInteger } from '@/utils'

const orderPayload = computed(() => {
  return shopCartStore.getOrderPayload
})

const handelChange = () => {
  let isGiveIntegral = state.isGiveIntegral //是否赠送积分
  let isGiveMoney = state.isGiveMoney //是否赠送金额

  if (!isGiveIntegral) {
    state.giveIntergral = ''
  }
  if (!isGiveMoney) {
    state.giveMoney = ''
  }
}
const onSelect = (item) => {
  if (item.id == state.packageId) {
    state.packageId = ''
    state.isGiveMoney = false
    state.giveMoney = ''
    state.isGiveIntegral = false
    state.giveIntergral = ''
    state.isGiveGrow = false
    state.giveGrow = ''
    state.rechargeMoeny = ''
  } else {
    state.packageId = item.id
    if (item.bonusPrice > 0) {
      state.isGiveMoney = true
      state.giveMoney = fenToYuan(item.bonusPrice)
    }
    if (item.pointPrice > 0) {
      state.isGiveIntegral = true
      state.giveIntergral = item.pointPrice
    }
    if (item.growPrice > 0) {
      state.isGiveGrow = true
      state.giveGrow = item.growPrice
    }
    state.rechargeMoeny = fenToYuan(item.payPrice)
  }
}
const orderId = ref()

const route = useRoute() // 路由
const { push, currentRoute } = useRouter() // 路由
const { delView } = useTagsViewStore() // 视图操作

const returnUrl = ref<string | undefined>(undefined) // 支付完的回调地址
const state = reactive({
  rechargeMoeny: '', //充值金额
  isGiveMoney: false, //是否赠送金额
  isGiveIntegral: false, //是否赠送积分
  isGiveCoupon: false, //是否赠送代金券
  giveMoney: '', //赠送金额
  giveIntergral: '', //赠送的积分
  isGiveGrow: false, //是否赠送经验值
  giveGrow: '', //赠送经验值
  packageId: '',
  packageList: [] as any, // 充值套餐
  orderPayload: {} as OrderApi.orderVO,
  orderInfo: {},
  // ========== 员工 ==========
  employeeStr: [],
  // 会员资产支付
  paymentMap: [],
  pay: [] as any,

  // ========== 分成 ==========
  rebateType: 0, //0统一 1单一
  // ========== 密码 ==========
  enalePassword: false, // 开启密码支付 true是
  payOrderId: '', //支付订单号
  // 补录
  isRepair: false, //是否补录
  repairDate: '', //补录日期
  //支付弹框提示
  showPayDialog: false //是否正在支付
})
/** 支付弹框 */
const payDialogRef = ref()
const openPayDialog = () => {
  state.pay = []
  state.showPayDialog = true
}
const handleUpdate = async () => {
  //这里是使用所以要 过滤当前支付取消的状态
  ElNotification({
    title: '提示',
    message: '订单完成',
    type: 'success'
  })
  playAudio('successPayment')
  // 更新订单状态
  closeSelectedTag()
}

// 获得钱包充值套餐列表
const getRechargeTabs = async () => {
  const data = await PayOrderApi.getWalletRechargePackageList()

  state.packageList = data
}
watch(
  () => orderPayload.value,
  () => {
    Object.assign(state.orderPayload, orderPayload.value)
  }
)

/**
 * 回到业务的 URL
 *
 * @param payResult 支付结果
 *                  ① success：支付成功
 *                  ② cancel：取消支付
 *                  ③ close：支付已关闭
 */
const goReturnUrl = (payResult) => {
  // 未配置的情况下，只能关闭
  if (!returnUrl.value) {
    delView(unref(currentRoute))
    return
  }

  const url =
    returnUrl.value.indexOf('?') >= 0
      ? returnUrl.value + '&payResult=' + payResult
      : returnUrl.value + '?payResult=' + payResult
  // 如果有配置，且是 http 开头，则浏览器跳转
  if (returnUrl.value.indexOf('http') === 0) {
    location.href = url
  } else {
    delView(unref(currentRoute))
    push({
      path: url
    })
  }
}

/** 选择员工 */
const UserShowcaseRef = ref()
const setEmployeeConfirm = () => {
  if (state.rebateType == 0) {
    if (autoConfirm.value) {
      onHandleConfirm()
    }
  }
}

/** 是否选择员工 */
const cartEmployeeText = computed(() => {
  let employeeText = ''
  if (state.rebateType == 0) {
    state.employeeStr.forEach((element: any, index: number) => {
      if (index == state.employeeStr.length - 1) {
        employeeText += element.employeeName + ' ' + element.proportion + '%'
      } else {
        employeeText += element.employeeName + ' ' + element.proportion + '%' + '|'
      }
    })
  }
  return employeeText
})

/** 确认订单 */
const autoConfirm = ref(false) //自动提交

const onHandleConfirm = async () => {
  if (state.rechargeMoeny == '') {
    message.error('请输入充值金额或选择充值套餐')
    return
  }
  if (cartEmployeeText.value == '') {
    if (state.rebateType == 0) {
      autoConfirm.value = true
      UserShowcaseRef.value.openSpuTableSelect()
    }

    return
  }
  if (state.orderPayload.isRepair) {
    if (state.orderPayload.repairDate == '') {
      message.error('请选择补录日期')
      return
    }
    if (state.orderPayload.remark == '') {
      message.error('请输入补录备注')
      return
    }
  }

  confirmOrder()
}
const confirmOrder = async () => {
  submitOrder()
}
const submitOrder = async () => {
  const data = await PayOrderApi.createWalletRecharge({
    userId: shopUserStore.getUser.id,
    payPrice: convertToInteger(state.rechargeMoeny),
    bonusEnable: state.isGiveMoney,
    bonusPrice: convertToInteger(state.giveMoney),
    pointsEnable: state.isGiveIntegral,
    pointsPrice: state.giveIntergral,
    employeeStr: state.employeeStr,
    isRepair: state.orderPayload.isRepair,
    repairDate: state.orderPayload.repairDate,
    packageId: state.packageId
  })
  orderId.value = data.id

  if (data.payOrderId) {
    state.payOrderId = data.payOrderId
    getOrderInfo(state.payOrderId)
  }

  // 关闭密码窗口
  // shopCartStore.closeCodeKeyBoard()
  // 更新购物车列表，如果来自购物车
}

/** 支付详情 */

const getOrderInfo = async (payOrderId) => {
  // 获得支付订单信息
  let params = {
    payOrderId: payOrderId,
    userId: shopUserStore.getUser.id
  }
  const data = await OrderApi.secondSettlementOrder(params)
  state.orderInfo = data
  state.paymentMap = data.paymentMap
  openPayDialog()
}

/** 初始化 */
onMounted(async () => {
  if (route.query.returnUrl) {
    returnUrl.value = decodeURIComponent(route.query.returnUrl as string)
  }
  await getRechargeTabs()
})
</script>

<style lang="scss" scoped>
:deep(.el-input__inner) {
  text-align: center;

  font-weight: bold;
  color: var(--el-color-primary);
}
</style>
